/*
 * Copyright 2007 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.starsource.forum.client.view;

import org.starsource.forum.client.domain.MessageObject;
import org.starsource.forum.client.handler.MessageUpdateHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;

/**
 * A simple example of an 'about' dialog box.
 */
public class FileUploadDialog extends DialogBox {

	interface Binder extends UiBinder<Widget, FileUploadDialog> { }
	private static final Binder binder = GWT.create(Binder.class);

	@UiField FormPanel uploadForm;
	@UiField FileUpload fileUpload;
	@UiField Button uploadButton;
	@UiField Button closeButton;
	@UiField FlexTable fileList;
	@UiField ScrollPanel fileScroll;
	
	private MessageObject messageObject;

	private MessageUpdateHandler messageUpdateHandler;

	public FileUploadDialog(MessageObject messageObject, MessageUpdateHandler messageUpdateHandler) {
		this.messageObject = messageObject;
		this.messageUpdateHandler = messageUpdateHandler;
		
		setText("上传文档");
		setWidget(binder.createAndBindUi(this));

		setAnimationEnabled(true);
		setGlassEnabled(true);

		uploadForm.setAction("fileupload?messageId=" + messageObject.getId());
		fileUpload.setName("uploadFormElement");
		uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
		uploadForm.setMethod(FormPanel.METHOD_POST);
		uploadForm.addSubmitHandler(new SubmitHandler() {

			@Override
			public void onSubmit(SubmitEvent event) {
				if (fileUpload.getFilename().length() == 0) {
					Window.alert("请选择您要上传的文件");
					event.cancel();
					uploadButton.setEnabled(true);
				}
			}
			
		});

		uploadForm.addSubmitCompleteHandler(new SubmitCompleteHandler() {

			@Override
			public void onSubmitComplete(SubmitCompleteEvent event) {
					uploadButton.setEnabled(true);
					String result = removePreTags(event.getResults());
					if ("OK".equals(result)) {
						fileList.setText(fileList.getRowCount(), 0, fileUpload.getFilename());
						fileScroll.scrollToBottom();
					} else {
						Window.alert(result);
					}
//				try {
//					
//					JSONObject jsonObject = JSONParser.parse(removePreTags(event.getResults())).isObject();
//					String code = jsonObject.get("code").isString().stringValue();
//					String message = jsonObject.get("message").isString().stringValue();
//					if (!"SUCCESS".equalsIgnoreCase(code)) {
//						String reason = jsonObject.get("reason").isString().stringValue();
//					} else {
//					}
//				} catch (Exception e) {
//					Window.alert("服务器发生了异常，请稍后再试，或联系网站维护人员。异常原因是：" + e.toString());
//				}
			}
			
		});
}

	@UiHandler("uploadButton")
	void onUploadClicked(ClickEvent event) {
		uploadButton.setEnabled(false);
		
		uploadForm.submit();
	}

	@UiHandler("closeButton")
	void onCloseClicked(ClickEvent event) {
		hide();
		this.messageUpdateHandler.onMessageUpdate(messageObject);
	}
	private String removePreTags(String response) {
		if (response.startsWith("<pre>")) {
			return response.substring("<pre>".length(), response.length() - "</pre>".length());
		} else if (response.startsWith("<PRE>")) {
			return response.substring("<PRE>".length(), response.length() - "</PRE>".length());
		} else {
			return response;
		}
	}

}
